package com.zhss.eshop.order.controller;

import com.zhss.eshop.common.constant.CloneDirection;
import com.zhss.eshop.order.domain.dto.OrderInfoDTO;
import com.zhss.eshop.order.domain.vo.CalculateCouponeDiscountPriceVO;
import com.zhss.eshop.order.domain.vo.OrderInfoVO;
import com.zhss.eshop.order.service.OrderInfoService;
import com.zhss.eshop.promotion.domain.dto.PromotionCouponDTO;
import com.zhss.eshop.promotion.domain.vo.PromotionCouponVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 订单管理controller组件
 * @author suyuan
 *
 */
@RestController
@RequestMapping("/order")
public class OrderInfoController {

	private static final Logger logger = LoggerFactory.getLogger(OrderInfoController.class);

	/**
	 * 订单管理service组件
	 */
	@Autowired
	private OrderInfoService orderInfoService;

//	@Autowired
//	private LoggedOrderStateManager orderStateManager;



	/**
	 * 计算订单价格`
	 * @param order
	 * @param deliveryAddress
	 * @return
	 */
	@PostMapping("/price")
	public OrderInfoVO calculateOrderPrice(@RequestBody OrderInfoVO order) {
		try {
			OrderInfoDTO resultOrder = orderInfoService.calculateOrderPrice(
					order.clone(OrderInfoDTO.class, CloneDirection.FORWARD));
			return resultOrder.clone(OrderInfoVO.class, CloneDirection.OPPOSITE);
		} catch (Exception e) {
			logger.error("error", e);
			return order;
		}
	}

	/**
	 * 计算优惠券抵扣的金额`
	 * @param order
	 * @param coupon
	 * @return
	 */
	@PostMapping("/coupon")
	public OrderInfoVO calculateCouponDiscountPrice(
			@RequestBody CalculateCouponeDiscountPriceVO vo) {
		try {
			OrderInfoVO order = vo.getOrder();
			PromotionCouponVO coupon = vo.getCoupon();

			OrderInfoDTO resultOrder = orderInfoService.calculateCouponDiscountPrice(
					order.clone(OrderInfoDTO.class, CloneDirection.FORWARD),
					coupon.clone(PromotionCouponDTO.class));
			return resultOrder.clone(OrderInfoVO.class, CloneDirection.OPPOSITE);
		} catch (Exception e) {
			logger.error("error", e);
			return vo.getOrder();
		}
	}

	/**
	 * 新建订单`
	 * @param order
	 * @return
	 */
	@PostMapping("/")
	public OrderInfoVO save(@RequestBody OrderInfoVO order) {
		try {
			OrderInfoDTO resultOrder = orderInfoService.insertSelective(order.clone(
					OrderInfoDTO.class, CloneDirection.FORWARD));
			return resultOrder.clone(OrderInfoVO.class, CloneDirection.OPPOSITE);
		} catch (Exception e) {
			logger.error("error", e);
			return order;
		}
	}

	/**
	 * 取消订单^
	 * @param id 订单id
	 * @return 处理结果
	 * @throws Exception
	 */
	@PutMapping("/cancel/{id}")
	public Boolean cancel(@PathVariable("id") Long id) {
		try {
			return orderInfoService.cancel(id);
		} catch (Exception e) {
			logger.error("error", e);
			return false;
		}
	}

}
